package org.andolphin.client.service;

import org.andolphin.client.Andolphin;
import org.andolphin.client.MainActivity;
import org.andolphin.client.R;
import org.andolphin.client.Result;
import org.andolphin.client.ResultHandler;
import org.andolphin.client.Andolphin.Prefs;
import org.andolphin.client.model.User;
import org.andolphin.client.utils.RemoteAccess;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

public class AuthService extends Service {

    private static final String TAG = AuthService.class.getName();

    private static final int NOTIFY_ID = 1;

    private final IAuthService.Stub binder = new IAuthService.Stub() {

        public void doAuth() throws RemoteException {
            final Context ctx = getApplicationContext();
            SharedPreferences prefs = getSharedPreferences(Andolphin.Prefs.ANDOLPHIN, Prefs.MODE);
            final String username = prefs.getString(Andolphin.Prefs.USERNAME, "");
            final String password = prefs.getString(Andolphin.Prefs.PASSWORD, "");
            final ResultHandler rh = new ResultHandler(new Handler() {
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case Result.CODE_SUCCESS:
                        loginSuccess(msg);
                        break;
                    default:
                        notifyError(msg);
                        break;
                    }
                }

            }, ctx);
            new Thread(new Runnable() {

                public void run() {
                    RemoteAccess.login(username, password, rh);
                }
            }).start();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    protected void loginSuccess(Message msg) {
        Result result = (Result) msg.getData().getSerializable(Result.KEY);
        User user = new User();
        user.fromJSON(result.getData().getRawData());
        SharedPreferences prefs = getSharedPreferences(Andolphin.Prefs.ANDOLPHIN, Prefs.MODE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(Andolphin.Prefs.USERNAME, user.getUsername());
        editor.putString(Andolphin.Prefs.PASSWORD, user.getPassword());
        editor.putString(Andolphin.Prefs.EMAIL, user.getEmail());
        editor.putString(Andolphin.Prefs.AUTH_TOKEN, user.getAuthToken());
        editor.putLong(Andolphin.Prefs.EXPIRE, user.getExpired().getTime());
        editor.commit();
    }

    protected void notifyError(Message msg) {
        Context ctx = getApplicationContext();
        Result result = (Result) msg.getData().getSerializable(Result.KEY);
        String message = result.getMessage();
        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.drawable.exclamation;
        CharSequence tickerText = getString(R.string.msg_error_occured, new Object[] { message });
        long when = System.currentTimeMillis();
        Notification notify = new Notification(icon, tickerText, when);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, Notification.FLAG_AUTO_CANCEL);

        notify.setLatestEventInfo(ctx, getString(R.string.msg_auth_invalid), tickerText, contentIntent);
        notifyManager.notify(NOTIFY_ID, notify);
    }
    
}
